package com.szrt.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.szrt.entity.UserEntity;
import com.szrt.listener.HelloSessionListener;


@SuppressWarnings("serial")
public class HelloController extends HttpServlet{
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String method = request.getParameter("method");
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String ip = request.getRemoteAddr();
		
		if("login".equals(method)){
			if(""==username || ""==password){
				request.setAttribute("error", "用户名和密码不能为空");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}else{
				System.out.println("用户"+username+"已经登录");
				HttpSession session = request.getSession();
				System.out.println(session.getId());
				//session.setAttribute("username", username);
				//session.setAttribute("password", password);
				session.setAttribute("user", new UserEntity(username,password,ip));
				
				HelloSessionListener.getList().add(new UserEntity(username,password,ip));
				
				request.getSession().setAttribute("list", HelloSessionListener.getList());
				response.sendRedirect("success.jsp");
			}
		}else if("cancel".equals(method)){
			HttpSession session = request.getSession();
			String name = (String) session.getAttribute("username");
			System.out.println("用户"+name+"已经退出");
			session.invalidate();
			response.sendRedirect("hello.do");
		}else if(null==method){
			response.sendRedirect("success.jsp");
		}
		
	}
	
	

}
